<template lang="pug">
  view
    view.status(:style="{ opacity: afterHeaderOpacity }")
    view.header
      view.before(:style="{ opacity: 1 - afterHeaderOpacity, zIndex: beforeHeaderzIndex }")
        view.back
          view.icon.xiangqian(@tap="back"  v-if="showBack")
        view.middle
        view.icon-btn
          view.icon.tongzhi(@tap="toMsg")
          view.icon.cart(@tap="cart")
      view.after(:style="{ opacity: afterHeaderOpacity, zIndex: afterHeaderzIndex }")
        view.back
          view.icon.xiangqian(@tap="back"  v-if="showBack")
        view.middle
          view(v-for="(anchor,index) in anchorlist"  :class="[selectAnchor==index ?'on':'']"  :key="index"  @tap="toAnchor(index)") {{anchor.name}}
        view.icon-btn
          view.icon.shop(@tap="toShop")
          view.icon.cart(@tap="cart")
    view.footer
      view.icons
        view.footer-btn(@tap="home")
          image( src="/static/img/common/home.png")
        view.footer-btn(@tap="toCall" )
          image( style="height:70upx;width:70upx" src="/static/img/common/contact.png")
        view.footer-btn(style="position:relative;left:10upx")
          button.footer-btn-bt(open-type="share")
            image(src="/static/img/common/wx.png")
      view.btn
        block(v-if="free==0")
          view.joinCart(@tap="joinCart") 加入购物车
          view.buy(@tap="buy") 立即购买
        block(v-if="free==1")
          view.buy(@tap="applyFreeProduct") 申请免费
    view.popup.service(:class="serviceClass"  @touchmove.stop.prevent="discard"  @tap="hideService")
      view.mask
      view.layer(@tap.stop="discard")
        view.content
          view.row(v-for="(item,index) in goodsData.service"  :key="index")
            view.title {{item.name}}
            view.description {{item.description}}
        view.btn
          view.button(@tap="hideService") 完成
    view.popup.spec(:class="specClass"  @touchmove.stop.prevent="discard"  @tap="hideSpec")
      view.mask
      view.layer(@tap.stop="discard")
        view.content
          view.title 选择规格：
          view.sp
            view(v-for="(item,index) in goodsData.spec"  :class="[index==selectSpec?'on':'']"  @tap="setSelectSpec(index)"  :key="index") {{item}}
          view.title 选择属性:
          view.sp
            view(v-for="(item,index) in selectAttr"  :class="[item.name==selectAttrValue?'on':'']"  @tap="setSelectAttr(item)"  :key="index") {{item.name}}
          view(v-if="selectAttrValue")
            view.length
              view.text 数量
              view.number
                view.sub(@tap.stop="sub")
                  view.icon.jian
                view.input(@tap.stop="discard")
                  input(type="number"  v-model="goodsData.number")
                view.add(@tap.stop="add")
                  view.icon.jia
              view.text 库存数量
              view.number                {{specstock}}
            view.length
              view.text 单价
              view.number.price(style="color:red")                ￥{{shopPrice}}
              view.text 总价
              view.number.price(style="color:red")                ￥{{shopPrice*goodsData.number}}
        view.btn
          view.button(@tap="hideSpec") 完成
    view.swiper-box
      swiper(circular="true"  autoplay="true"  @change="swiperChange")
        swiper-item(v-for="swiper in swiperList"  :key="swiper.id")
          image(:src="swiper.img + $pictureResolution(0, 750)")
      view.indicator {{currentSwiper+1}}/{{swiperList.length}}
    view.info-box.goods-info
      view.price(v-if="goodsData.minPrice < goodsData.maxPrice") ￥{{goodsData.minPrice}} - {{goodsData.maxPrice}}
      view.price(v-if="goodsData.minPrice === goodsData.maxPrice") ￥{{goodsData.price}}
      view.title {{goodsData.name}}
    view.info-box.spec
      view.row(@tap="showService")
        view.text 服务
        view.content
          view.serviceitem(v-for="(item,index) in goodsData.service"  :key="index") {{item.name}}
        view.arrow
          view.icon.xiangyou
      view.row(@tap="showSpec(false)")
        view.text 选择规格：
        view.content
          view.sp
            view(v-for="(item,index) in goodsData.spec"  :key="index"  :class="[index==selectSpec?'on':'']") {{item}}
        view.arrow
          view.icon.xiangyou
    view.info-box.comments(id="comments")
      view.text(style="background-color: #EBEDF0;border-radius: 15rpx;color: #FF5E5E;"  @tap="toShop()")         进店逛逛
      view.description
        view.title ———— 商品详情 ————
        view.content
          rich-text(:nodes="descriptionStr")
</template>

<script>
import * as _ from "underscore"

export default {
  data() {
    return {
      free: 0,
      //session
      sessionid: '',
      hearder: '',
      shopPrice: '',
      specstock: '',
      selectAttrValue: '',
      //控制渐变标题栏的参数
      beforeHeaderzIndex: 11,//层级
      afterHeaderzIndex: 10,//层级
      beforeHeaderOpacity: 1,//不透明度
      afterHeaderOpacity: 0,//不透明度
      //是否显示返回按钮
      // #ifndef MP
      showBack: true,
      // #endif
      //轮播主图数据
      swiperList: [],
      //轮播图下标
      currentSwiper: 0,
      anchorlist: [],//导航条锚点
      selectAnchor: 0,//选中锚点
      serviceClass: '',//服务弹窗css类，控制开关动画
      specClass: '',//规格弹窗css类，控制开关动画
      shareClass: '',//分享弹窗css类，控制开关动画
      // 商品信息
      goodsData: {
        service: [
          {name: "", description: ""},
          {name: "", description: ""},
          {name: "", description: "此商品享受7"}
        ],
        spec: [],
        specid: [],
        specprice: [],
        specstock: [],
        number: 1,
        comment: {
          number: 1,
          userface: '',
          username: '',
          content: ''
        },
        price: 0.0,
        name: "",
        minPrice: '',
        maxPrice: ''
      },
      shopId: 0,
      pic: '',
      selectSpec: null,//选中规格
      isKeep: false,//收藏
      //商品描述html
      descriptionStr: '',
    };
  },
  computed: {
    selectAttr() {
      let key = _.get(this.goodsData, ['spec', this.selectSpec], '')
      return _.get(this.goodsData, ['objectSkus', key])
    }
  },
  onShareAppMessage(res) {
    return {
      title: '各位好朋友们，快来帮帮我【' + this.goodsData.name + '】免费拿回家' + '竟然可以免费拿🙏🙏🙏',
      path: '/pages/goods/goods?cid=' + this.goodsData.id + "&shopId=" + this.shopId,
      success: function (res) {
        // 转发成功，可以把当前页面的链接发送给后端，用于记录当前页面被转发了多少次或其他业务
        // wx.request({
        //   url: app.buildUrl("/member/share"),
        //   data: {
        //     url: utils.getCurrentPageUrlWithArgs()
        //   },
        //   success: function(res) {
        //     //console.log('成功');
        //   }
        // });
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  onLoad(option) {
    // #ifdef MP
    //小程序隐藏返回按钮
    this.showBack = false;
    // #endif
    //option为object类型，会序列化上个页面传递的参数
    console.log(option.cid); //打印出上个页面传递的参数。
    console.log(option.free);
    this.free = option.free == null ? 0 : option.free;
    this.shopId = option.shopId == null ? "29" : option.shopId;
    this.goodsData.id = option.cid;
    console.log(this.$api.product.getProductInfo + "?id=" + option.cid + "&shop_id=" + this.shopId);
    this.$Request.post(this.$api.product.getProductInfo + "?id=" + option.cid + "&shop_id=" + this.shopId).then(res => {
      console.log('resresresresresres', res);
      if (res.code == 200) {
        this.goodsData.name = res.data.name;
        this.goodsData.price = res.data.price;
        let imgs = res.data.detailHtml.split(',')
        let str = ''
        imgs.forEach(item => {
          str += `<img width="100%" src="${item}"/>`
        })
        this.descriptionStr = '<div style="text-align:center;">' + str + '</div>';
        this.shopId = this.shopId == 0 ? res.data.shopId : this.shopId;
        this.swiperList = [];
        this.pic = res.data.pic;
        // var data = {
        // 			'id':res.data.productSn,
        // 			'img':this.pic
        // }
        //this.swiperList.push(data);
        let array = res.data.albumPics.split(',');
        for (var i = 0; i < array.length; i++) {

          var data = {
            'id': this.goodsData.id,
            'img': array[i]
          }
          this.swiperList.push(data);
        }
        this.goodsData.spec = [];
        this.goodsData.specid = [];
        let arrayskus = res.data.skus;
        this.goodsData.minPrice = res.data.minPrice;
        this.goodsData.maxPrice = res.data.maxPrice;
        this.goodsData.objectSkus = {}
        for (var i = 0; i < arrayskus.length; i++) {
          console.log(i, arrayskus[i]);
          this.goodsData.price = arrayskus[i].price;
          this.goodsData.specid.push(arrayskus[i].skuCode);
          this.goodsData.spec.push(arrayskus[i].sp1);
          this.goodsData.specprice.push(arrayskus[i].price);
          this.goodsData.specstock.push(arrayskus[i].stock);

          if (this.goodsData.objectSkus[arrayskus[i].sp1]) {
            this.goodsData.objectSkus[arrayskus[i].sp1].push({
              name: arrayskus[i].sp4,
              specstock: arrayskus[i].stock,
              ...arrayskus[i]
            })
          } else {
            this.goodsData.objectSkus[arrayskus[i].sp1] = [{
              name: arrayskus[i].sp4,
              specstock: arrayskus[i].stock,
              ...arrayskus[i]
            }]
          }
          if (i == 0) {
            this.selectSpec = 0;
            this.goodsData.price = this.goodsData.specprice[0];
            this.goodsData.stock = this.goodsData.specstock[0];
          }
        }
        this.goodsData.spec = Array.from(new Set(this.goodsData.spec))

        if (this.free == 1) this.goodsData.price = 0;
      }
    })
  },
  onReady() {
    this.calcAnchor();//计算锚点高度，页面数据是ajax加载时，请把此行放在数据渲染完成事件中执行以保证高度计算正确
  },
  onPageScroll(e) {
    //锚点切换
    this.selectAnchor = e.scrollTop >= this.anchorlist[2].top ? 2 : e.scrollTop >= this.anchorlist[1].top ? 1 : 0;
    //导航栏渐变
    let tmpY = 375;
    e.scrollTop = e.scrollTop > tmpY ? 375 : e.scrollTop;
    this.afterHeaderOpacity = e.scrollTop * (1 / tmpY);
    this.beforeHeaderOpacity = 1 - this.afterHeaderOpacity;
    //切换层级
    this.beforeHeaderzIndex = e.scrollTop > 0 ? 10 : 11;
    this.afterHeaderzIndex = e.scrollTop > 0 ? 11 : 10;
  },
  methods: {
    //轮播图指示器
    swiperChange(event) {
      this.currentSwiper = event.detail.current;
    },
    //消息列表
    toMsg() {
      uni.navigateTo({
        url: 'free'
        //url:'../msg/msg'
      })
    },
    toCall() {
      uni.makePhoneCall({
        phoneNumber: '13367318731',
        success: (res) => {
          console.log('调用成功!')
        },
        fail: (res) => {
          console.log('调用失败!')
        }
      });
    },
    //预览商铺
    toShop() {
      uni.navigateTo({
        url: "/pages/tabBar/home/shop?shopid=" + this.shopId
      })
    },
    // 客服
    toChat() {
      uni.navigateTo({
        url: "../msg/chat/chat?name=客服008"
      })
    },
    // 首页
    home() {
      uni.switchTab({
        url: "../tabBar/home/home"
      })
    },
    // 购物车
    cart() {
      uni.switchTab({
        url: "../tabBar/cart/cart"
      })
    },
    // 分享
    share() {
      this.shareClass = 'show';
    },
    hideShare() {
      this.shareClass = 'hide';
      setTimeout(() => {
        this.shareClass = 'none';
      }, 150);
    },
    //收藏
    keep() {
      this.isKeep = this.isKeep ? false : true;
      this.sessionid = uni.getStorageSync("sessionid");
      this.hearder = uni.getStorageSync("hearder");
      if (this.sessionid == null || this.sessionid == '') {
        uni.showToast({title: "请先登录！"});
        return;
      }

      if (this.isKeep == false) {
        var header = this.hearder;
        var sessionid = this.sessionid;
        var data = {'memberId': 0, 'productId': this.goodsData.id};
        this.$Request.post(this.$api.member.deleteProduct, data, header + sessionid).then(res => {

          if (res.code == 200) {
            uni.showToast({title: "已删除收藏"});
          } else {
            uni.showToast({title: "删除收藏失败"});
          }
        })
      } else {
        var header = this.hearder;
        var sessionid = this.sessionid;
        var data = {
          'productCollection': {'memberId': 0, 'productId': this.goodsData.id}
        };
        this.$Request.post(this.$api.member.addProduct, data, header + sessionid).then(res => {

          if (res.code == 200) {
            uni.showToast({title: "已加入收藏"});
          } else {
            uni.showToast({title: "加入收藏失败"});
          }
        })
      }
    },
    // 加入购物车
    joinCart() {
      this.sessionid = uni.getStorageSync("sessionid");
      this.hearder = uni.getStorageSync("hearder");
      if (this.sessionid == null || this.sessionid == '') {
        //uni.showToast({title: "请先登录！"});
        uni.navigateTo({
          url: '/pages/login/login'
        })
        return;
      }
      var data = {};
      if (this.selectAttrValue) {
        var header = this.hearder;
        var sessionid = this.sessionid;
        let row = this.selectAttr.find(item => {
          return item.name === this.selectAttrValue
        })
        console.log(row)
        this.$Request.get(this.$api.cart.addSkuCode + row.skuCode + "?quantity=" + this.goodsData.number, data, header + sessionid).then(res => {

          if (res.code == 200) {
            //return this.showSpec(()=>{
            uni.showToast({title: "已加入购物车"});
            //});
          } else {
            uni.showToast({title: "加入购物车失败"});
          }
        })
      } else {
        uni.showToast({title: "请先选择规格"});
      }
    },
    applyFreeProduct() {
      this.sessionid = uni.getStorageSync("sessionid");
      this.hearder = uni.getStorageSync("hearder");
      if (this.sessionid == null || this.sessionid == '') {
        //uni.showToast({title: "请先登录！"});
        uni.navigateTo({
          url: '/pages/login/login'
        })
        return;
      }
      var freeProduct = {
        "skuCode": this.goodsData.specid[this.selectSpec],
      };
      var data = {};
      if (this.selectSpec != null) {
        var header = this.hearder;
        var sessionid = this.sessionid;
        this.$Request.get(this.$api.product.applyFreeProductSimple + '?skuCode=' + freeProduct.skuCode, data, header + sessionid).then(res => {

          if (res.code == 200) {
            //return this.showSpec(()=>{
            //{"code":200,"message":"操作成功","data":{"id":3,"productId":null,"skuId":316,"memberId":52,"startDate":"2020-08-14 19:03:02","satisfyNum":5,"endDate":"2020-09-01 19:03:09","qrcodeUrl":"https://mbeg168.cn/portal/sso/recommendUser/3","status":0,"note":null},"success":true}
            uni.navigateTo({
              url: 'free?cid=' + res.data.id + '&productname=' + this.goodsData.name + "&free=1"
            })
            //uni.showToast({title: "申请成功"});
            //});
          } else {
            uni.showToast({title: "申请失败"});
          }
        })
      } else {
        uni.showToast({title: "请先选择规格"});
      }
    },

    //立即购买
    buy() {
      if (!this.selectAttrValue) {
        return uni.showToast({title: "请先选择规格和属性", icon: 'error'});
      }
      if (this.sessionid == null) {
        //uni.showToast({title: "请先登录！"});
        uni.navigateTo({
          url: '/pages/login/login'
        })
        return;
      }

      if (this.selectAttrValue == null) {
        return this.showSpec(() => {
          this.toConfirmation();
        });
      }
      this.toConfirmation();
    },
    //商品评论
    toRatings() {
      uni.navigateTo({
        url: 'ratings/ratings'
      })
    },
    //跳转确认订单页面
    toConfirmation() {
      let tmpList = [];
      let row = this.selectAttr.find(item => {
        return item.name === this.selectAttrValue
      })
      let goods = {
        id: this.goodsData.id,
        sku: this.goodsData.specid[this.selectSpec],
        img: this.pic,
        name: this.goodsData.name,
        spec: '规格:' + row.sp1 + ":" + row.name,
        price: this.goodsData.price,
        number: this.goodsData.number,
        ...row
      };
      tmpList.push(goods);
      uni.setStorage({
        key: 'buylist',
        data: tmpList,
        success: () => {
          uni.navigateTo({
            url: '../order/confirmation?standby=1'
          })
        }
      })
    },
    //跳转评论列表
    showComments(goodsid) {

    },
    //选择规格
    setSelectSpec(index) {
      this.selectSpec = index;
      this.selectAttrValue = ''
      this.goodsData.price = this.goodsData.specprice[index];
      this.goodsData.stock = this.goodsData.specstock[index];
    },
    //选择属性
    setSelectAttr(item) {
      this.selectAttrValue = item.name;
      this.specstock = item.specstock
      this.shopPrice = item.price
    },

    //减少数量
    sub() {
      if (this.goodsData.number <= 1) {
        return;
      }
      this.goodsData.number--;
    },
    //增加数量
    add() {
      if (this.goodsData.stock <= this.goodsData.number) {
        uni.showToast({title: "库存不足", icon: 'none'});
        return;
      }
      this.goodsData.number++;
    },
    //跳转锚点
    toAnchor(index) {
      this.selectAnchor = index;
      uni.pageScrollTo({scrollTop: this.anchorlist[index].top, duration: 200});
    },
    //计算锚点高度
    calcAnchor() {
      this.anchorlist = [
        {name: '主图', top: 0},
        {name: '评价', top: 0},
        {name: '详情', top: 0}
      ]
      let commentsView = uni.createSelectorQuery().select("#comments");
      commentsView.boundingClientRect((data) => {
        let statusbarHeight = 0;
        //APP内还要计算状态栏高度
        // #ifdef APP-PLUS
        statusbarHeight = plus.navigator.getStatusbarHeight()
        // #endif
        let headerHeight = uni.upx2px(100);
        this.anchorlist[1].top = data.top - headerHeight - statusbarHeight;
        this.anchorlist[2].top = data.bottom - headerHeight - statusbarHeight;

      }).exec();
    },
    //返回上一页
    back() {
      uni.navigateBack();
    },
    //服务弹窗
    showService() {
      console.log('show');
      this.serviceClass = 'show';
    },
    //关闭服务弹窗
    hideService() {
      this.serviceClass = 'hide';
      setTimeout(() => {
        this.serviceClass = 'none';
      }, 200);
    },
    //规格弹窗
    showSpec(fun) {
      console.log('show');
      this.specClass = 'show';
      this.specCallback = fun;
    },
    specCallback() {
      return;
    },
    //关闭规格弹窗
    hideSpec() {
      this.specClass = 'hide';
      //回调

      this.selectSpec && this.specCallback && this.specCallback();
      this.specCallback = false;
      setTimeout(() => {
        this.specClass = 'none';
      }, 200);
    },
  }
};
</script>

<style lang="scss">
@import "./goods";
</style>
